using Google.Protobuf;
using LFrameworkAOT;
using System;
using System.Collections.Generic;

namespace LFramework
{
    public class HttpManager
    {
        /// <summary>
        /// 正式账号服务器Url
        /// </summary>
        private string m_WebAccountUrl;
        /// <summary>
        /// 测试账号服务器Url
        /// </summary>
        private string m_TestWebAccountUrl;
        /// <summary>
        /// 是否测试环境
        /// </summary>
        private bool m_IsTest;
        /// <summary>
        /// 真实账号服务器Url
        /// </summary>
        public string RealWebAccountUrl { get { return "http://" + RealIpAndPort + "/"; } }
        public string RealIpAndPort { get { return m_IsTest ? m_TestWebAccountUrl : m_WebAccountUrl; } }

        public HttpManager()
        {
            m_WebAccountUrl = GameLaunch.ParamsSettings.WebAccountUrl;
            m_TestWebAccountUrl = GameLaunch.ParamsSettings.TestWebAccountUrl;
            m_IsTest = GameLaunch.ParamsSettings.IsTest;
        }

        #region Get
        public void Get(string url, Action<HttpCallBackArgs> callBack = null)
        {
            HttpRoutine.Create().Get(url, callBack);
        }
        #endregion

        #region Post
        public void Post(string url, string json = null, Action<HttpCallBackArgs> callBack = null, Dictionary<string, string> addHeaderDic = null, bool isAddDefaultHeader = true)
        {
            HttpRoutine.Create().PostByJson(url, json, callBack, addHeaderDic, isAddDefaultHeader);
        }

        public void Post<T>(string url, IMessage msg, Action<T> suc_cb, Action<string> fail_cb,Dictionary<string, string> addHeaderDic = null, bool isAddDefaultHeader = true) where T : IMessage, new()
        {
            HttpRoutine.Create().PostByBytes(url, msg.ToByteArray(), (args) => 
            {
                if (args.HasError)
                    fail_cb?.Invoke(args.Value);
                else 
                {
                    T obj = new T();
                    obj.MergeFrom(args.Data);

                    suc_cb?.Invoke(obj);
                }
            }, addHeaderDic, isAddDefaultHeader);
        }
        #endregion

        public void Dispose()
        {
            
        }
    }
}